package id.co.shuba.spamobile;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.content.AsyncTaskLoader;

public abstract class SimpleCursorLoader extends AsyncTaskLoader<Cursor> {
    private Cursor _cursor;

    public SimpleCursorLoader(Context context) {
        super(context);
    }

    @Override
    public abstract Cursor loadInBackground();

    @Override
    public void deliverResult(Cursor cursor) {
        if (isReset()) {
            if (cursor != null) {
                cursor.close();
            }
            return;
        }
        Cursor oldCursor = _cursor;
        _cursor = cursor;

        if (isStarted()) {
            super.deliverResult(cursor);
        }

        if (oldCursor != null && oldCursor != cursor && !oldCursor.isClosed()) {
            oldCursor.close();
        }
    }
    
    @Override
    protected void onStartLoading() {
        if (_cursor != null) {
            deliverResult(_cursor);
        }
        if (takeContentChanged() || _cursor == null) {
            forceLoad();
        }
    }

    @Override
    protected void onStopLoading() {        
        cancelLoad();
    }

    @Override
    public void onCanceled(Cursor cursor) {
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
    }

    @Override
    protected void onReset() {
        super.onReset();
        
        onStopLoading();

        if (_cursor != null && !_cursor.isClosed()) {
            _cursor.close();
        }
        _cursor = null;
    }
}